#include "mqtt_cloud.h"
#include "device_state_manager.h"

// 外部函数声明
#include "smart_home_ui.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <stdarg.h>
#include <stddef.h>
#include <openssl/hmac.h>
#include <openssl/ossl_typ.h>
#include "base/MQTTAsync.h"
#include "cJSON.h"

// 云平台连接配置 - 这些是您已经配置好的参数
static char *uri = "tcp://b9980dc36d.iotda-device.cn-south-4.myhuaweicloud.com:1883";
static char *username = "68955e20fabf3d7ebcdc8c17_myNodeId"; 
static char *password = "asdzxc123";

// MQTT配置参数
static int gQOS = 1;
static int keepAliveInterval = 120;
static int connectTimeout = 30;
static int retryInterval = 10;

// MQTT客户端和状态
static MQTTAsync client = NULL;
static mqtt_status_t current_status = MQTT_DISCONNECTED;
static mqtt_status_callback_t status_callback = NULL;
static mqtt_message_callback_t message_callback = NULL;
static light_control_callback_t light_control_callback = NULL;  // 灯光控制回调函数
static ac_control_callback_t ac_control_callback = NULL;        // 空调控制回调函数
static music_control_callback_t music_control_callback = NULL;  // 音乐控制回调函数
static int mqttClientCreateFlag = 0;
static int retryTimes = 0;

// 加密相关常量
#define TRY_MAX_TIME               100
#define SHA256_ENCRYPTION_LENGRH   32
#define TIME_STAMP_LENGTH          20  // 增加时间戳长度以避免截断
#define PASSWORD_ENCRYPT_LENGTH    64
#define CLIENT_TIME_LENGTH         20  // 增加时间客户端长度

// 工具函数声明
static char* get_client_timestamp(void);
static char* combine_strings(int strAmount, char *str1, ...);
static int string_length(char *str);
static void string_malloc(char **str, int length);
static int copy_str_value(char **dst, const char *src, int length);
static int get_encrypted_password(char **timestamp, char **encryptedPwd);
static int encrypt_with_hmac_sha256(const char *inputData, char **inputKey, int inEncryDataLen, char *outData);

// 命令处理函数声明
static void handle_light_control_command(cJSON *json, const char *topic);
static void handle_ac_control_command(cJSON *json, const char *topic);
static void handle_music_control_command(cJSON *json, const char *topic);
static void send_command_response(cJSON *original_command, const char *topic, int code, const char *message, const char *result);
static char* extract_request_id_from_topic(const char *topic);

// MQTT回调函数
static void mqtt_connect_success(void *context, MQTTAsync_successData *response);
static void mqtt_connect_failure(void *context, MQTTAsync_failureData *response);
static void mqtt_connection_lost(void *context, char *cause);
static int mqtt_message_arrive(void *context, char *topicName, int topicLen, MQTTAsync_message *message);
static void publish_success(void *context, MQTTAsync_successData *response);
static void publish_failure(void *context, MQTTAsync_failureData *response);

// 时间戳生成
static char* get_client_timestamp() {
    time_t t;
    struct tm *lt;
    
    time(&t);
    lt = gmtime(&t);
    if (lt == NULL) {
        return NULL;
    }
    
    char *dest_str = malloc(CLIENT_TIME_LENGTH + 1);
    if (dest_str == NULL) {
        return NULL;
    }
    
    memset(dest_str, 0, CLIENT_TIME_LENGTH + 1);
    // 使用更安全的格式化，限制年份为4位数
    int year = lt->tm_year + 1900;
    if (year > 9999) year = 9999; // 限制年份最大值
    int result = snprintf(dest_str, CLIENT_TIME_LENGTH + 1, "%04d%02d%02d%02d", 
                         year, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour);
    if (result >= CLIENT_TIME_LENGTH + 1) {
        // 如果截断了，使用更简单的格式
        snprintf(dest_str, CLIENT_TIME_LENGTH + 1, "%ld", (long)t % 10000000000L);
    }
    return dest_str;
}

// 字符串工具函数
static int string_length(char *str) {
    if (str == NULL) return 0;
    int len = 0;
    char *temp_str = str;
    while (*temp_str++ != '\0') len++;
    return len;
}

static void string_malloc(char **str, int length) {
    if (length <= 0) return;
    *str = malloc(length);
    if (*str == NULL) return;
    memset(*str, 0, length);
}

static int copy_str_value(char **dst, const char *src, int length) {
    if (length <= 0) return 0;
    *dst = malloc(length + 1);
    if (*dst == NULL) return -1;
    memset(*dst, 0, length + 1);
    strncat(*dst, src, length);
    return 0;
}

static char* combine_strings(int strAmount, char *str1, ...) {
    if (str1 == NULL) return NULL;
    
    // 首先计算总长度
    int total_length = string_length(str1) + 1; // +1 for null terminator
    
    va_list args;
    va_start(args, str1);
    
    // 计算所有字符串的总长度
    int remaining = strAmount - 1;
    while (remaining > 0) {
        char *temStr = va_arg(args, char*);
        if (temStr != NULL) {
            total_length += string_length(temStr);
        }
        remaining--;
    }
    va_end(args);
    
    // 分配足够的内存
    char *result = malloc(total_length);
    if (result == NULL) return NULL;
    
    // 复制第一个字符串
    strcpy(result, str1);
    
    // 重新开始遍历参数
    va_start(args, str1);
    remaining = strAmount - 1;
    while (remaining > 0) {
        char *temStr = va_arg(args, char*);
        if (temStr != NULL) {
            strcat(result, temStr);
        }
        remaining--;
    }
    va_end(args);
    
    return result;
}

// HMAC-SHA256加密
static int encrypt_with_hmac_sha256(const char *inputData, char **inputKey, int inEncryDataLen, char *outData) {
    if (inputData == NULL || (*inputKey) == NULL) {
        printf("encrypt_with_hmac_sha256(): 输入参数无效\n");
        return -1;
    }
    
    int keyLen = strlen(*inputKey);
    if (keyLen < 10 || keyLen > TIME_STAMP_LENGTH) {
        printf("encrypt_with_hmac_sha256(): 时间戳长度无效: %d\n", keyLen);
        return -1;
    }
    
    char *end = NULL;
    unsigned int mac_length = 0;
    unsigned int tryTime = 1;
    int lenData = strlen(inputData);
    long timeTmp = strtol(*inputKey, &end, 10);
    
    unsigned char *hmac_temp = HMAC(EVP_sha256(), *inputKey, keyLen, 
                                 (const unsigned char*)inputData, lenData, NULL, &mac_length);
    
    while (mac_length != SHA256_ENCRYPTION_LENGRH) {
        tryTime++;
        if (tryTime > TRY_MAX_TIME) {
            printf("encrypt_with_hmac_sha256(): 达到最大加密尝试次数\n");
            return -1;
        }
        
        timeTmp++;
        snprintf(*inputKey, TIME_STAMP_LENGTH + 1, "%ld", timeTmp);
        keyLen = strlen(*inputKey);  // 更新密钥长度
        hmac_temp = HMAC(EVP_sha256(), *inputKey, keyLen, 
                        (const unsigned char*)inputData, lenData, NULL, &mac_length);
    }
    
    int uiIndex, uiLoop;
    char ucHex;
    
    for (uiIndex = 0, uiLoop = 0; uiLoop < inEncryDataLen; uiLoop++) {
        ucHex = (hmac_temp[uiLoop] >> 4) & 0x0F;
        outData[uiIndex++] = (ucHex <= 9) ? (ucHex + '0') : (ucHex + 'a' - 10);
        
        ucHex = hmac_temp[uiLoop] & 0x0F;
        outData[uiIndex++] = (ucHex <= 9) ? (ucHex + '0') : (ucHex + 'a' - 10);
    }
    
    outData[uiIndex] = '\0';
    return 0;
}

static int get_encrypted_password(char **timestamp, char **encryptedPwd) {
    if (password == NULL) return -1;
    
    char *temp_encrypted_pwd = NULL;
    string_malloc(&temp_encrypted_pwd, PASSWORD_ENCRYPT_LENGTH + 1);
    if (temp_encrypted_pwd == NULL) {
        printf("get_encrypted_password(): 内存不足\n");
        return -1;
    }
    
    int ret = encrypt_with_hmac_sha256(password, timestamp, SHA256_ENCRYPTION_LENGRH, temp_encrypted_pwd);
    if (ret != 0) {
        printf("get_encrypted_password(): 加密失败 %d\n", ret);
        free(temp_encrypted_pwd);
        return -1;
    }
    
    if (copy_str_value(encryptedPwd, (const char*)temp_encrypted_pwd, PASSWORD_ENCRYPT_LENGTH) < 0) {
        printf("get_encrypted_password(): 内存不足\n");
        free(temp_encrypted_pwd);
        return -1;
    }
    
    free(temp_encrypted_pwd);
    return 0;
}

// MQTT回调函数实现
static void mqtt_connect_success(void *context, MQTTAsync_successData *response) {
    retryTimes = 0;
    current_status = MQTT_CONNECTED;
    printf("MQTT连接成功\n");
    
    if (status_callback) {
        status_callback(current_status);
    }
}

static void mqtt_connect_failure(void *context, MQTTAsync_failureData *response) {
    retryTimes++;
    current_status = MQTT_CONNECTION_FAILED;
    printf("MQTT连接失败: messageId %d, code %d, message %s\n", 
           response->token, response->code, response->message);
    
    if (status_callback) {
        status_callback(current_status);
    }
}

static void mqtt_connection_lost(void *context, char *cause) {
    current_status = MQTT_DISCONNECTED;
    printf("MQTT连接丢失: %s\n", cause);
    
    if (status_callback) {
        status_callback(current_status);
    }
}

static int mqtt_message_arrive(void *context, char *topicName, int topicLen, MQTTAsync_message *message) {
    printf("收到MQTT消息: topic=%s, payload=%s\n", topicName, (char*)message->payload);
    
    // 检查是否是云平台命令消息
    if (strstr(topicName, "/sys/commands/") != NULL) {
        printf("收到云平台命令，开始解析...\n");
        
        // 解析JSON命令
        cJSON *json = cJSON_Parse((char*)message->payload);
        if (json == NULL) {
            printf("JSON解析失败\n");
            return 1;
        }
        
        // 获取服务ID和命令名称（华为云IoTDA标准格式）
        cJSON *service_id = cJSON_GetObjectItem(json, "service_id");
        cJSON *command_name = cJSON_GetObjectItem(json, "command_name");
        
        if (service_id && command_name && service_id->valuestring && command_name->valuestring) {
            printf("服务ID: %s, 命令名称: %s\n", service_id->valuestring, command_name->valuestring);
            
            // 处理智能家居服务的命令
            if (strcmp(service_id->valuestring, "smartHome") == 0) {
                if (strcmp(command_name->valuestring, "LightControl") == 0) {
                    handle_light_control_command(json, topicName);
                } else if (strcmp(command_name->valuestring, "AcControl") == 0) {
                    handle_ac_control_command(json, topicName);
                } else if (strcmp(command_name->valuestring, "MusicControl") == 0) {
                    handle_music_control_command(json, topicName);
                } else {
                    printf("未知的命令名称: %s\n", command_name->valuestring);
                    send_command_response(json, topicName, 400, "参数错误", "未知的命令名称");
                }
            } else {
                printf("未知的服务ID: %s\n", service_id->valuestring);
                send_command_response(json, topicName, 400, "参数错误", "未知的服务ID");
            }
            // 可以在这里添加其他服务和命令的处理
        } else {
            printf("命令格式错误：缺少service_id或command_name\n");
            send_command_response(json, topicName, 400, "参数错误", "命令格式错误");
        }
        
        cJSON_Delete(json);
    }
    
    if (message_callback) {
        message_callback(topicName, (char*)message->payload);
    }
    
    return 1;
}

static void publish_success(void *context, MQTTAsync_successData *response) {
    printf("消息发布成功: messageId=%d\n", response ? response->token : -1);
    printf("数据已成功上传到华为云IoTDA平台\n\n");
}

static void publish_failure(void *context, MQTTAsync_failureData *response) {
    printf("消息发布失败\n");
    if (response) {
        printf("错误详情: messageId=%d, code=%d, message=%s\n", 
               response->token, response->code, response->message);
    }
    printf("数据上传到华为云IoTDA平台失败\n\n");
}

// 从topic中提取request_id
static char* extract_request_id_from_topic(const char *topic) {
    // topic格式: $oc/devices/{device_id}/sys/commands/request_id={request_id}
    const char *request_id_prefix = "request_id=";
    char *request_id_pos = strstr(topic, request_id_prefix);
    
    if (request_id_pos == NULL) {
        printf("警告: 无法从topic中提取request_id: %s\n", topic);
        return NULL;
    }
    
    // 跳过 "request_id=" 前缀
    request_id_pos += strlen(request_id_prefix);
    
    // 查找request_id的结束位置（遇到'/'或字符串结束）
    char *end_pos = strchr(request_id_pos, '/');
    int request_id_len;
    if (end_pos != NULL) {
        request_id_len = end_pos - request_id_pos;
    } else {
        request_id_len = strlen(request_id_pos);
    }
    
    // 分配内存并复制request_id
    char *request_id = malloc(request_id_len + 1);
    if (request_id == NULL) {
        printf("错误: 无法为request_id分配内存\n");
        return NULL;
    }
    
    strncpy(request_id, request_id_pos, request_id_len);
    request_id[request_id_len] = '\0';
    
    printf("提取到request_id: %s\n", request_id);
    return request_id;
}

// 公共接口实现
int mqtt_cloud_init(void) {
    printf("初始化MQTT云平台连接模块\n");
    current_status = MQTT_DISCONNECTED;
    return 0;
}

int mqtt_cloud_connect(void) {
    char *encrypted_password = NULL;
    
    if (!mqttClientCreateFlag) {
        char *temp_authMode = "_0_0_";
        
        MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
        conn_opts.cleansession = 1;
        conn_opts.keepAliveInterval = keepAliveInterval;
        conn_opts.connectTimeout = connectTimeout;
        conn_opts.retryInterval = retryInterval;
        conn_opts.onSuccess = mqtt_connect_success;
        conn_opts.onFailure = mqtt_connect_failure;
        
        char *loginTimestamp = get_client_timestamp();
        if (loginTimestamp == NULL) {
            return -1;
        }
        
        int encryptedRet = get_encrypted_password(&loginTimestamp, &encrypted_password);
        if (encryptedRet != 0) {
            free(loginTimestamp);
            return -1;
        }
        
        char *clientId = combine_strings(3, username, temp_authMode, loginTimestamp);
        free(loginTimestamp);
        
        int createRet = MQTTAsync_create(&client, uri, clientId, MQTTCLIENT_PERSISTENCE_NONE, NULL);
        free(clientId);
        
        if (createRet) {
            printf("MQTT客户端创建失败: %d\n", createRet);
            if (encrypted_password) free(encrypted_password);
            return -1;
        } else {
            mqttClientCreateFlag = 1;
            printf("MQTT客户端创建成功\n");
        }
        
        MQTTAsync_setCallbacks(client, NULL, mqtt_connection_lost, mqtt_message_arrive, NULL);
        
        conn_opts.username = username;
        conn_opts.password = encrypted_password;
        
        printf("开始连接MQTT服务器...\n");
        current_status = MQTT_CONNECTING;
        
        int ret = MQTTAsync_connect(client, &conn_opts);
        if (ret) {
            printf("MQTT连接启动失败: %d\n", ret);
            current_status = MQTT_CONNECTION_FAILED;
            if (encrypted_password) free(encrypted_password);
            return -1;
        }
        
        if (encrypted_password) {
            free(encrypted_password);
            encrypted_password = NULL;
        }
    }
    
    return 0;
}

void mqtt_cloud_disconnect(void) {
    if (client && mqttClientCreateFlag) {
        MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
        MQTTAsync_disconnect(client, &disc_opts);
        current_status = MQTT_DISCONNECTED;
        printf("MQTT连接已断开\n");
    }
}

int mqtt_cloud_publish_device_data(const device_data_t* data) {
    if (!client || current_status != MQTT_CONNECTED) {
        printf("MQTT未连接，无法发布数据\n");
        return -1;
    }
    
    // 创建JSON数据
    cJSON *root = cJSON_CreateObject();
    cJSON *services = cJSON_CreateArray();
    cJSON *service = cJSON_CreateObject();
    cJSON *properties = cJSON_CreateObject();
    
    // 添加设备属性
    // 空调属性
    cJSON_AddBoolToObject(properties, "ac_power", data->ac_power);
    cJSON_AddNumberToObject(properties, "ac_temperature", data->ac_temperature);
    cJSON_AddNumberToObject(properties, "ac_mode", data->ac_mode);
    cJSON_AddNumberToObject(properties, "ac_fan_speed", data->ac_fan_speed);
    
    // 四个独立灯光属性
    cJSON_AddBoolToObject(properties, "light1_power", data->light1_power);
    cJSON_AddBoolToObject(properties, "light2_power", data->light2_power);
    cJSON_AddBoolToObject(properties, "light3_power", data->light3_power);
    cJSON_AddBoolToObject(properties, "light4_power", data->light4_power);
    
    // LED属性
    cJSON_AddBoolToObject(properties, "led_power", data->led_power);
    
    // 环境监测属性
    cJSON_AddNumberToObject(properties, "temperature", data->temperature);
    cJSON_AddNumberToObject(properties, "humidity", data->humidity);
    cJSON_AddNumberToObject(properties, "smoke_density", data->smoke_density);
    
    // 音乐播放器属性
    cJSON_AddBoolToObject(properties, "music_playing", data->music_playing);
    cJSON_AddNumberToObject(properties, "music_volume", data->music_volume);
    cJSON_AddStringToObject(properties, "current_song", data->current_song);
    
    // 呼叫触发器属性
    cJSON_AddBoolToObject(properties, "dad_call_trigger", data->dad_call_trigger);
    cJSON_AddBoolToObject(properties, "mom_call_trigger", data->mom_call_trigger);
    cJSON_AddBoolToObject(properties, "son_call_trigger", data->son_call_trigger);
    cJSON_AddBoolToObject(properties, "daughter_call_trigger", data->daughter_call_trigger);
    
    cJSON_AddStringToObject(service, "service_id", "smartHome");
    cJSON_AddItemToObject(service, "properties", properties);
    cJSON_AddItemToArray(services, service);
    cJSON_AddItemToObject(root, "services", services);
    
    char *json_string = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    
    if (!json_string) {
        printf("JSON数据创建失败\n");
        return -1;
    }
    
    // 打印要发送的JSON数据到控制台，便于调试
    printf("\n=== 发送到云平台的数据 ===\n");
    printf("主题: %s\n", "$oc/devices/68955e20fabf3d7ebcdc8c17_myNodeId/sys/properties/report");
    printf("JSON数据:\n%s\n", json_string);
    printf("=========================\n\n");
    
    // 发布数据
    char *report_topic = combine_strings(3, "$oc/devices/", username, "/sys/properties/report");
    
    MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
    MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
    
    opts.onSuccess = publish_success;
    opts.onFailure = publish_failure;
    
    pubmsg.payload = json_string;
    pubmsg.payloadlen = strlen(json_string);
    pubmsg.qos = gQOS;
    pubmsg.retained = 0;
    
    int ret = MQTTAsync_sendMessage(client, report_topic, &pubmsg, &opts);
    
    free(report_topic);
    free(json_string);
    
    if (ret != 0) {
        printf("数据发布启动失败: 错误代码=%d\n", ret);
        return -1;
    }
    
    printf("设备数据发布请求已发送，等待云平台响应...\n");
    return 0;
}

int mqtt_cloud_subscribe_commands(void) {
    if (!client || current_status != MQTT_CONNECTED) {
        printf("MQTT未连接，无法订阅命令\n");
        return -1;
    }
    
    char *command_topic = combine_strings(3, "$oc/devices/", username, "/sys/commands/#");
    
    MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
    int qos = 1;
    int ret = MQTTAsync_subscribe(client, command_topic, qos, &opts);
    
    free(command_topic);
    
    if (ret != MQTTASYNC_SUCCESS) {
        printf("命令订阅失败: %d\n", ret);
        return -1;
    }
    
    printf("已订阅云平台命令\n");
    return 0;
}

void mqtt_cloud_set_status_callback(mqtt_status_callback_t callback) {
    status_callback = callback;
}

void mqtt_cloud_set_message_callback(mqtt_message_callback_t callback) {
    message_callback = callback;
}

void mqtt_cloud_set_light_control_callback(light_control_callback_t callback) {
    light_control_callback = callback;
}

void mqtt_cloud_set_ac_control_callback(ac_control_callback_t callback) {
    ac_control_callback = callback;
}

void mqtt_cloud_set_music_control_callback(music_control_callback_t callback) {
    music_control_callback = callback;
}

mqtt_status_t mqtt_cloud_get_status(void) {
    return current_status;
}

void mqtt_cloud_cleanup(void) {
    if (client && mqttClientCreateFlag) {
        mqtt_cloud_disconnect();
        MQTTAsync_destroy(&client);
        mqttClientCreateFlag = 0;
        client = NULL;
    }
    printf("MQTT云平台模块已清理\n");
}

// 简化的数据上传接口 - 获取完整状态后只更新指定字段
int mqtt_upload_ac_data(bool power, int temperature, int mode, int fan_speed) {
    // 获取当前完整设备状态
    device_state_t current_device_state = get_current_device_states();
    
    device_data_t *data = calloc(1, sizeof(device_data_t));
    if (!data) {
        printf("mqtt_upload_ac_data: 内存分配失败\n");
        return -1;
    }
    
    // 复制完整设备状态
    data->ac_power = power;  // 使用传入的新值
    data->ac_temperature = temperature;
    data->ac_mode = mode;
    data->ac_fan_speed = fan_speed;
    
    // 复制其他设备状态
    data->light1_power = current_device_state.light1_state;
    data->light2_power = current_device_state.light2_state;
    data->light3_power = current_device_state.light3_state;
    data->light4_power = current_device_state.light4_state;
    data->led_power = false; // LED状态
    
    data->temperature = 25; // 环境温度
    data->humidity = 60;    // 环境湿度
    data->smoke_density = current_device_state.smoke_concentration;
    
    data->music_playing = current_device_state.music_playing;
    data->music_volume = current_device_state.music_volume;
    strcpy(data->current_song, "春江花月夜"); // 默认歌曲
    
    // 保持当前呼叫状态
    data->dad_call_trigger = current_device_state.dad_call_triggered;
    data->mom_call_trigger = current_device_state.mom_call_triggered;
    data->son_call_trigger = current_device_state.son_call_triggered;
    data->daughter_call_trigger = current_device_state.daughter_call_triggered;
    
    int result = mqtt_cloud_publish_device_data(data);
    free(data);
    return result;
}

int mqtt_upload_lights_data(bool light1, bool light2, bool light3, bool light4) {
    // 获取当前完整设备状态
    device_state_t current_device_state = get_current_device_states();
    
    device_data_t *data = calloc(1, sizeof(device_data_t));
    if (!data) {
        printf("mqtt_upload_lights_data: 内存分配失败\n");
        return -1;
    }
    
    // 设置灯光状态
    data->light1_power = light1;
    data->light2_power = light2;
    data->light3_power = light3;
    data->light4_power = light4;
    data->led_power = (light1 || light2 || light3 || light4);
    
    // 复制其他设备状态
    data->ac_power = current_device_state.ac_power;
    data->ac_temperature = current_device_state.ac_temperature;
    data->ac_mode = current_device_state.ac_mode;
    data->ac_fan_speed = current_device_state.ac_fan_speed;
    
    data->temperature = 25; // 环境温度
    data->humidity = 60;    // 环境湿度
    data->smoke_density = current_device_state.smoke_concentration;
    
    data->music_playing = current_device_state.music_playing;
    data->music_volume = current_device_state.music_volume;
    strcpy(data->current_song, "春江花月夜");
    
    // 保持当前呼叫状态
    data->dad_call_trigger = current_device_state.dad_call_triggered;
    data->mom_call_trigger = current_device_state.mom_call_triggered;
    data->son_call_trigger = current_device_state.son_call_triggered;
    data->daughter_call_trigger = current_device_state.daughter_call_triggered;
    
    int result = mqtt_cloud_publish_device_data(data);
    free(data);
    return result;
}

int mqtt_upload_led_data(bool power) {
    // 使用upload_all_device_data来保持完整状态
    upload_all_device_data();
    return 0;
}

int mqtt_upload_environment_data(int temperature, int humidity, int smoke_density) {
    // 使用upload_all_device_data来保持完整状态
    upload_all_device_data();
    return 0;
}

int mqtt_upload_music_data(bool playing, int volume, const char* song) {
    // 使用upload_all_device_data来保持完整状态
    upload_all_device_data();
    return 0;
}

// 上传呼叫数据到华为云平台
// is_call: true表示呼叫，false表示挂断
int mqtt_upload_call_data(int contact_index, bool is_call, const char* message) {
    // 验证参数
    if (contact_index < 0 || contact_index >= 4) {
        printf("mqtt_upload_call_data: 参数无效\n");
        return -1;
    }
    
    // 更新设备状态管理器中的状态
    switch (contact_index) {
        case 0: // 爸爸
            printf("mqtt_upload_call_data: 设置爸爸呼叫状态为 %s\n", is_call ? "true" : "false");
            update_dad_call_triggered(is_call);
            break;
        case 1: // 妈妈
            printf("mqtt_upload_call_data: 设置妈妈呼叫状态为 %s\n", is_call ? "true" : "false");
            update_mom_call_triggered(is_call);
            break;
        case 2: // 儿子
            printf("mqtt_upload_call_data: 设置儿子呼叫状态为 %s\n", is_call ? "true" : "false");
            update_son_call_triggered(is_call);
            break;
        case 3: // 女儿
            printf("mqtt_upload_call_data: 设置女儿呼叫状态为 %s\n", is_call ? "true" : "false");
            update_daughter_call_triggered(is_call);
            break;
        default:
            printf("mqtt_upload_call_data: 无效的联系人索引: %d\n", contact_index);
            return -1;
    }
    
    // 不需要立即发布数据，由定时任务统一发布
    return 0;
}

// 灯光控制命令处理函数
static void handle_light_control_command(cJSON *json, const char *topic) {
    printf("处理灯光控制命令...\n");
    
    // 获取命令参数（华为云IoTDA标准格式）
    cJSON *paras = cJSON_GetObjectItem(json, "paras");
    if (!paras) {
        printf("命令参数为空\n");
        send_command_response(json, topic, 400, "参数错误", "缺少paras字段");
        return;
    }
    
    // 解析灯光控制参数
    cJSON *light_id = cJSON_GetObjectItem(paras, "light_id");
    cJSON *action = cJSON_GetObjectItem(paras, "action");
    
    if (!light_id || !action) {
        printf("缺少必要的命令参数: light_id 或 action\n");
        send_command_response(json, topic, 400, "参数错误", "缺少light_id或action参数");
        return;
    }
    
    int light_index = light_id->valueint;
    const char *action_str = action->valuestring;
    
    printf("灯光控制命令: 灯%d, 动作: %s\n", light_index, action_str);
    
    // 验证参数
    if (light_index < 1 || light_index > 4) {
        printf("无效的灯光ID: %d (应为1-4)\n", light_index);
        send_command_response(json, topic, 400, "参数错误", "无效的灯光ID，应为1-4");
        return;
    }
    
    bool new_state = false;
    if (strcmp(action_str, "on") == 0) {
        new_state = true;
    } else if (strcmp(action_str, "off") == 0) {
        new_state = false;
    } else {
        printf("无效的动作: %s (应为 'on' 或 'off')\n", action_str);
        send_command_response(json, topic, 400, "参数错误", "无效的动作，应为on或off");
        return;
    }
    
    // 调用灯光控制回调函数
    if (light_control_callback) {
        light_control_callback(light_index, new_state);
        printf("执行灯光控制: 灯%d -> %s\n", light_index, new_state ? "开启" : "关闭");

        // 更新系统信息框
        char system_msg[128];
        const char* light_names[] = {"", "客厅灯", "卧室灯", "厨房灯", "阳台灯"};
        snprintf(system_msg, sizeof(system_msg), "服务器命令: %s%s", 
                light_names[light_index], new_state ? "开启" : "关闭");
        update_system_message(system_msg);

        // 发送成功响应给云平台
        char result_msg[128];
        snprintf(result_msg, sizeof(result_msg), "%s%s成功", 
                light_names[light_index], new_state ? "开启" : "关闭");
        send_command_response(json, topic, 0, "success", result_msg);
    } else {
        printf("警告: 灯光控制回调函数未设置\n");
        send_command_response(json, topic, 500, "内部错误", "灯光控制回调函数未设置");
    }
}

// 空调控制命令处理函数
static void handle_ac_control_command(cJSON *json, const char *topic) {
    printf("处理空调控制命令...\n");
    
    // 获取命令参数（华为云IoTDA标准格式）
    cJSON *paras = cJSON_GetObjectItem(json, "paras");
    if (!paras) {
        printf("空调命令参数为空\n");
        send_command_response(json, topic, 400, "参数错误", "缺少paras字段");
        return;
    }
    
    // 获取操作类型
    cJSON *action = cJSON_GetObjectItem(paras, "action");
    if (!action || !action->valuestring) {
        printf("缺少action参数\n");
        send_command_response(json, topic, 400, "参数错误", "缺少action参数");
        return;
    }
    
    const char *action_str = action->valuestring;
    printf("空调控制命令: 动作=%s\n", action_str);
    
    // 处理不同的空调控制命令
    if (strcmp(action_str, "power") == 0) {
        // 开关空调
        cJSON *power_state = cJSON_GetObjectItem(paras, "power");
        if (!power_state) {
            printf("缺少power参数\n");
            send_command_response(json, topic, 400, "参数错误", "缺少power参数");
            return;
        }
        
        bool power = (strcmp(power_state->valuestring, "on") == 0);
        if (ac_control_callback) {
            ac_control_callback("power", power ? 1 : 0);
        
        // 更新系统信息框
        char system_msg[64];
        snprintf(system_msg, sizeof(system_msg), "服务器命令: 空调%s", power ? "开启" : "关闭");
        update_system_message(system_msg);
        
        char result_msg[64];
        snprintf(result_msg, sizeof(result_msg), "空调%s成功", power ? "开启" : "关闭");
        send_command_response(json, topic, 0, "success", result_msg);
    } else {
            printf("警告: 空调控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "空调控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "temperature") == 0) {
        // 调节温度
        cJSON *temperature = cJSON_GetObjectItem(paras, "temperature");
        if (!temperature) {
            printf("缺少temperature参数\n");
            send_command_response(json, topic, 400, "参数错误", "缺少temperature参数");
            return;
        }
        
        int temp_value = temperature->valueint;
        if (temp_value < 16 || temp_value > 30) {
            printf("无效的温度值: %d (应为16-30)\n", temp_value);
            send_command_response(json, topic, 400, "参数错误", "温度应在16-30度之间");
            return;
        }
        
        if (ac_control_callback) {
            ac_control_callback("temperature", temp_value);
        
        // 更新系统信息框
        char system_msg[64];
        snprintf(system_msg, sizeof(system_msg), "服务器命令: 空调温度设置为%d°C", temp_value);
        update_system_message(system_msg);
        
        char result_msg[64];
        snprintf(result_msg, sizeof(result_msg), "空调温度设置为%d°C成功", temp_value);
        send_command_response(json, topic, 0, "success", result_msg);
    } else {
            printf("警告: 空调控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "空调控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "mode") == 0) {
        // 切换模式
        cJSON *mode = cJSON_GetObjectItem(paras, "mode");
        if (!mode) {
            printf("缺少mode参数\n");
            send_command_response(json, topic, 400, "参数错误", "缺少mode参数");
            return;
        }
        
        int mode_value = mode->valueint;
        if (mode_value < 0 || mode_value > 4) {
            printf("无效的模式值: %d (应为0-4)\n", mode_value);
            send_command_response(json, topic, 400, "参数错误", "模式应为0-4 (0:制冷, 1:制热, 2:送风, 3:除湿, 4:自动)");
            return;
        }
        
        if (ac_control_callback) {
            ac_control_callback("mode", mode_value);
        const char* mode_names[] = {"制冷", "制热", "送风", "除湿", "自动"};
        
        // 更新系统信息框
        char system_msg[64];
        snprintf(system_msg, sizeof(system_msg), "服务器命令: 空调模式切换为%s", mode_names[mode_value]);
        update_system_message(system_msg);
        
        char result_msg[64];
        snprintf(result_msg, sizeof(result_msg), "空调模式切换为%s成功", mode_names[mode_value]);
        send_command_response(json, topic, 0, "success", result_msg);
    } else {
            printf("警告: 空调控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "空调控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "fan_speed") == 0) {
        // 调节风速
        cJSON *fan_speed = cJSON_GetObjectItem(paras, "fan_speed");
        if (!fan_speed) {
            printf("缺少fan_speed参数\n");
            send_command_response(json, topic, 400, "参数错误", "缺少fan_speed参数");
            return;
        }
        
        int speed_value = fan_speed->valueint;
        if (speed_value < 0 || speed_value > 3) {
            printf("无效的风速值: %d (应为0-3)\n", speed_value);
            send_command_response(json, topic, 400, "参数错误", "风速应为0-3 (0:自动, 1:低, 2:中, 3:高)");
            return;
        }
        
        if (ac_control_callback) {
            ac_control_callback("fan_speed", speed_value);
        const char* fan_speed_names[] = {"自动", "低", "中", "高"};
        
        // 更新系统信息框
        char system_msg[64];
        snprintf(system_msg, sizeof(system_msg), "服务器命令: 空调风速设置为%s", fan_speed_names[speed_value]);
        update_system_message(system_msg);
        
        char result_msg[64];
        snprintf(result_msg, sizeof(result_msg), "空调风速设置为%s成功", fan_speed_names[speed_value]);
        send_command_response(json, topic, 0, "success", result_msg);
    } else {
            printf("警告: 空调控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "空调控制回调函数未设置");
        }
    }
    else {
        printf("未知的空调控制动作: %s\n", action_str);
        send_command_response(json, topic, 400, "参数错误", "未知的控制动作");
    }
}

// 音乐播放器控制命令处理函数
static void handle_music_control_command(cJSON *json, const char *topic) {
    printf("处理音乐播放器控制命令...\n");
    
    // 获取命令参数（华为云IoTDA标准格式）
    cJSON *paras = cJSON_GetObjectItem(json, "paras");
    if (!paras) {
        printf("音乐命令参数为空\n");
        send_command_response(json, topic, 400, "参数错误", "缺少paras字段");
        return;
    }
    
    // 获取操作类型
    cJSON *action = cJSON_GetObjectItem(paras, "action");
    if (!action || !action->valuestring) {
        printf("缺少action参数\n");
        send_command_response(json, topic, 400, "参数错误", "缺少action参数");
        return;
    }
    
    const char *action_str = action->valuestring;
    printf("音乐播放器控制命令: 动作=%s\n", action_str);
    
    // 处理不同的音乐控制命令
    if (strcmp(action_str, "play") == 0) {
        // 播放音乐
        if (music_control_callback) {
            music_control_callback("play", 1);
        
        // 更新系统信息框
        update_system_message("服务器命令: 音乐播放");
        
        send_command_response(json, topic, 0, "success", "音乐播放成功");
    } else {
            printf("警告: 音乐控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "音乐控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "pause") == 0) {
        // 暂停音乐
        if (music_control_callback) {
            music_control_callback("pause", 0);
        
        // 更新系统信息框
        update_system_message("服务器命令: 音乐暂停");
        
        send_command_response(json, topic, 0, "success", "音乐暂停成功");
    } else {
            printf("警告: 音乐控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "音乐控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "stop") == 0) {
        // 停止音乐
        if (music_control_callback) {
            music_control_callback("stop", 0);
        
        // 更新系统信息框
        update_system_message("服务器命令: 音乐停止");
        
        send_command_response(json, topic, 0, "success", "音乐停止成功");
    } else {
            printf("警告: 音乐控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "音乐控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "next") == 0) {
        // 下一首
        if (music_control_callback) {
            music_control_callback("next", 1);
        
        // 更新系统信息框
        update_system_message("服务器命令: 下一首");
        
        send_command_response(json, topic, 0, "success", "切换到下一首成功");
    } else {
            printf("警告: 音乐控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "音乐控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "previous") == 0) {
        // 上一首
        if (music_control_callback) {
            music_control_callback("previous", 1);
        
        // 更新系统信息框
        update_system_message("服务器命令: 上一首");
        
        send_command_response(json, topic, 0, "success", "切换到上一首成功");
    } else {
            printf("警告: 音乐控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "音乐控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "volume") == 0) {
        // 调节音量
        cJSON *volume = cJSON_GetObjectItem(paras, "volume");
        if (!volume) {
            printf("缺少volume参数\n");
            send_command_response(json, topic, 400, "参数错误", "缺少volume参数");
            return;
        }
        
        int volume_value = volume->valueint;
        if (volume_value < 0 || volume_value > 100) {
            printf("无效的音量值: %d (应为0-100)\n", volume_value);
            send_command_response(json, topic, 400, "参数错误", "音量应为0-100");
            return;
        }
        
        if (music_control_callback) {
            music_control_callback("volume", volume_value);
        
        // 更新系统信息框
        char system_msg[64];
        snprintf(system_msg, sizeof(system_msg), "服务器命令: 音量设置为%d", volume_value);
        update_system_message(system_msg);
        
        char result_msg[64];
        snprintf(result_msg, sizeof(result_msg), "音量设置为%d成功", volume_value);
        send_command_response(json, topic, 0, "success", result_msg);
    } else {
            printf("警告: 音乐控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "音乐控制回调函数未设置");
        }
    }
    else if (strcmp(action_str, "song") == 0) {
        // 切换歌曲
        cJSON *song_index = cJSON_GetObjectItem(paras, "song_index");
        if (!song_index) {
            printf("缺少song_index参数\n");
            send_command_response(json, topic, 400, "参数错误", "缺少song_index参数");
            return;
        }
        
        int index_value = song_index->valueint;
        if (index_value < 0 || index_value > 10) { // 假设最多支持10首歌
            printf("无效的歌曲索引: %d (应为0-10)\n", index_value);
            send_command_response(json, topic, 400, "参数错误", "歌曲索引应为0-10");
            return;
        }
        
        if (music_control_callback) {
            music_control_callback("song", index_value);
        
        // 更新系统信息框
        char system_msg[64];
        snprintf(system_msg, sizeof(system_msg), "服务器命令: 切换到歌曲%d", index_value);
        update_system_message(system_msg);
        
        char result_msg[64];
        snprintf(result_msg, sizeof(result_msg), "切换到歌曲%d成功", index_value);
        send_command_response(json, topic, 0, "success", result_msg);
    } else {
            printf("警告: 音乐控制回调函数未设置\n");
            send_command_response(json, topic, 500, "内部错误", "音乐控制回调函数未设置");
        }
    }
    else {
        printf("未知的音乐控制动作: %s\n", action_str);
        send_command_response(json, topic, 400, "参数错误", "未知的控制动作");
    }
}

// 发送命令响应给云平台（华为云IoTDA标准格式）
static void send_command_response(cJSON *original_command, const char *topic, int code, const char *message, const char *result) {
    printf("命令执行结果: code=%d, message=%s, result=%s\n", code, message, result);
    
    if (!client || current_status != MQTT_CONNECTED) {
        printf("MQTT未连接，无法发送命令响应\n");
        return;
    }
    
    // 从原始topic中提取request_id
    char *request_id = extract_request_id_from_topic(topic);
    if (request_id == NULL) {
        printf("无法提取request_id，跳过响应发送\n");
        return;
    }
    
    // 构建响应JSON
    cJSON *response = cJSON_CreateObject();
    cJSON_AddNumberToObject(response, "result_code", code);
    cJSON_AddStringToObject(response, "response_name", "COMMAND_RESPONSE");
    
    cJSON *paras = cJSON_CreateObject();
    cJSON_AddStringToObject(paras, "result", result);
    cJSON_AddStringToObject(paras, "message", message);
    cJSON_AddItemToObject(response, "paras", paras);
    
    char *response_payload = cJSON_PrintUnformatted(response);
    cJSON_Delete(response);
    
    if (!response_payload) {
        printf("创建响应JSON失败\n");
        free(request_id);
        return;
    }
    
    // 构建响应topic: $oc/devices/{device_id}/sys/commands/response/request_id={request_id}
    char *response_topic = combine_strings(4, "$oc/devices/", username, "/sys/commands/response/request_id=", request_id);
    free(request_id);
    
    if (!response_topic) {
        printf("创建响应topic失败\n");
        free(response_payload);
        return;
    }
    
    printf("\n=== 发送命令响应到云平台 ===\n");
    printf("响应主题: %s\n", response_topic);
    printf("响应JSON: %s\n", response_payload);
    printf("============================\n\n");
    
    // 发布响应消息
    MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
    MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
    
    opts.onSuccess = publish_success;
    opts.onFailure = publish_failure;
    
    pubmsg.payload = response_payload;
    pubmsg.payloadlen = strlen(response_payload);
    pubmsg.qos = gQOS;
    pubmsg.retained = 0;
    
    int ret = MQTTAsync_sendMessage(client, response_topic, &pubmsg, &opts);
    
    free(response_topic);
    free(response_payload);
    
    if (ret != 0) {
        printf("命令响应发布启动失败: 错误代码=%d\n", ret);
    } else {
        printf("命令响应发布请求已发送，等待云平台确认...\n");
    }
    
    // 可选：立即上传设备状态，让云平台知道当前设备状态
    if (code == 0) {
        printf("命令执行成功，准备上传最新设备状态...\n");
        // 这里可以触发一次状态上报
        // upload_all_device_data(); // 这个函数在smart_home_ui.c中定义
    } else {
        // 命令执行失败，更新系统信息框
        char error_msg[128];
        snprintf(error_msg, sizeof(error_msg), "命令执行失败: %s", message);
        update_system_message(error_msg);
    }
}
